package com.md.model.excel;

import com.md.model.base.ColorInfo;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColor;

import java.util.Optional;

/**
 * @author 刘骄阳
 * 2024-05-14 18:58
 */
@Data
@EqualsAndHashCode(callSuper = true)
public class ExcelColorInfo extends ColorInfo {

  public static ExcelColorInfo getColorInfo(final XSSFFont font, final StylesTable stylesTable) {
    ExcelColorInfo colorInfo = new ExcelColorInfo();
    Optional.ofNullable(font.getCTFont().getColorList()).ifPresent(ctColors -> {
      if (ctColors.isEmpty()) {
        return;
      }
      colorInfo.setThemeRGB(stylesTable.getTheme().getThemeColor((int) ctColors.get(0).getTheme()).getRGB());
    });
    Optional.ofNullable(font.getXSSFColor()).ifPresent(xssfColor -> {
      colorInfo.setTint(xssfColor.getTint());
      colorInfo.setRgb(xssfColor.getRGB());
    });
    return colorInfo;
  }

  public static ExcelColorInfo getColorInfo(final CTColor ctColor, final StylesTable stylesTable) {
    if (ctColor == null) {
      return null;
    }
    ExcelColorInfo colorInfo = new ExcelColorInfo();
    if (ctColor.getRgb() == null || ctColor.getRgb().length == 0) {
      Optional.of(XSSFColor.from(ctColor, stylesTable.getIndexedColors())).map(xssfColor ->
          stylesTable.getTheme().getThemeColor(xssfColor.getTheme())).map(XSSFColor::getRGB)
        .ifPresent(colorInfo::setThemeRGB);
    } else {
      colorInfo.setRgb(ctColor.getRgb());
    }
    colorInfo.setTint(ctColor.getTint());
    return colorInfo;
  }


}
